//
//  HomeViewController.swift
//  MT
//
//  Created by ooops on 2019/7/18.
//  Copyright © 2019年 张强. All rights reserved.
//

import UIKit
import MTCategory
import JXPagingView
import JXCategoryView
import RxSwift
import RxCocoa
import YPNavigationBarTransition

class MTPartyTaskViewController: BaseViewController {
    
    public var listViewDidScrollCallback: ((UIScrollView) -> ())?
    private var listViewDidRefreshCallback: (() -> Void)?
    
    private lazy var partyProvider: MTProvider<MTCreateTaskAPI> = {
        let provider = MTProvider<MTCreateTaskAPI>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    private var result: [MTPartyTaskListInfoModel] = []
    private var currentPage: Int = 1
    private let pageSize: Int = 20
    private var loadType: Int = 1
    private var clubType: MTPartyListTaskType = .myTask
    private var subclubType: MTPartyListTaskType = .default
    
    
    /// 新建
    /// - Parameters:
    ///   - taskType: 俱乐部类型 - MTPartyListTaskType
    ///   - callback: 刷新完成回调
    convenience init(taskType: MTPartyListTaskType, taskSubType: MTPartyListTaskType, callback: (() -> Void)?) {
        self.init()
        self.listViewDidRefreshCallback = callback
        self.clubType = clubType
        self.subclubType = taskSubType
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.theme.background
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        loadFirst()
    }
    
    override func refreshView() {
        loadFirst()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        tableView.frame = view.bounds
    }
    
    
    // MARK: - 加载数据
    /// - Parameter loadMore: 是否加载更多
    private func loadData(loadMore: Bool) {
        var queryParam: [String : Any] = ["curPage" : currentPage, "pageSize" : pageSize, "type" : self.clubType.rawValue]
        if self.subclubType != .default {
            queryParam.updateValue(self.subclubType.rawValue, forKey: "subType")
        }
        
        MTCreateTaskTool.queryPartyList(provider: partyProvider, parameters: queryParam, complete: { [weak self] (model) in
            
            guard let weakSelf = self else { return }
            weakSelf.comporseData(model: model, loadMore: loadMore)
        }) { [weak self] (_) in
            guard let weakSelf = self else { return }
            if !loadMore {
                weakSelf.listViewDidRefreshCallback?()
            }
        }
    }
    
    private func comporseData(model: MTPartyListModel?, loadMore: Bool) {
        weak var weakSelf = self
        weakSelf?.tableView.mj_footer?.endRefreshing()
        weakSelf?.tableView.mj_header?.endRefreshing()
        if weakSelf?.currentPage == 1 {
            weakSelf?.tableView.mj_footer?.state = .idle
        }
        
        if let m = model {
            debugPrint("message: ", m.message ?? "")
            if let r = m.result {
                if (m.page?.pages == weakSelf?.currentPage) {
                    weakSelf?.tableView.mj_footer?.endRefreshingWithNoMoreData()
                }
                if loadMore == true {
                    weakSelf?.result = weakSelf!.result + r
                } else {
                    weakSelf?.result = r
                }
                
                weakSelf?.hiddenHF(isHidden: weakSelf?.result.count == 0)
            } else {
                weakSelf?.hiddenHF(isHidden: true)
            }
            
            DispatchQueue.main.async {
                if !loadMore {
                    weakSelf?.listViewDidRefreshCallback?()
                }
                weakSelf?.tableView.reloadData()
            }
        }
    }
    
    @objc private func hiddenHF(isHidden: Bool) {
        self.tableView.mj_header?.isHidden = isHidden
        self.tableView.mj_footer?.isHidden = isHidden
    }
    
    @objc func loadFirst() {
        self.currentPage = 1
        
        loadData(loadMore: false)
    }
    
    @objc private func loadMore() {
        
        self.currentPage = self.currentPage + 1
        
        loadData(loadMore: true)
        
    }
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(MTJoinTaskCell.self, forCellReuseIdentifier: MTJoinTaskCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.backgroundColor = UIColor(hex: 0xf4f4f4)
        table.showsVerticalScrollIndicator = false
        table.isScrollEnabled = false
        table.showsVerticalScrollIndicator = false
        table.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        table.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(loadFirst))
        table.mj_footer?.ignoredScrollViewContentInsetBottom = 25
        table.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        table.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.loadFirst()

        }
        return table
    }()
}

extension MTPartyTaskViewController: WXApiDelegate {
    
    
    
}

extension MTPartyTaskViewController: UITableViewDelegate, UITableViewDataSource {
    
    //MARK: UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.result.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: MTJoinTaskCell = tableView.dequeueReusableCell(withIdentifier: MTJoinTaskCell.reuseIdentity(), for: indexPath) as! MTJoinTaskCell
        let model = self.result[indexPath.row]
        cell.model = model
        return cell
    }
    
    func configureCell(cell: MTJoinTaskCell, forRowAt indexPath: IndexPath) {
        
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.result[indexPath.row]
        guard let pushId = model.id else { return }
        if model.status == .ended {
            MBProgressHUD_JChat.show(text: "聚会任务已结束", view: self.view, 1)
            return
        }
        let vc = MTPartyTaskDetailViewController(partyTaskId: pushId)
        vc.certification = model.certification
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 160
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
    
}


extension MTPartyTaskViewController: MTClubRichListViewCellDelegate {
    
    func joinClub(cell: MTClubRichListViewCell, model: MTClubRichListResultModel?) {
        
        
    }
    
}

extension MTPartyTaskViewController: JXPagingViewListViewDelegate {
    func listView() -> UIView {
        return view
    }

    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }

    func listScrollView() -> UIScrollView {
        return self.tableView
    }

    func listWillAppear() {
        debugPrint("\(self.title ?? ""):\(#function)")
    }

    func listDidAppear() {
        debugPrint("\(self.title ?? ""):\(#function)")
    }

    func listWillDisappear() {
        debugPrint("\(self.title ?? ""):\(#function)")
    }

    func listDidDisappear() {
        debugPrint("\(self.title ?? ""):\(#function)")
    }
}


extension MTPartyTaskViewController {
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}
